/*
 * HttpDownloader.cpp
 *
 *  Created on: 26.09.2012
 *      Author: Sergey
 */

#include <QtGui>
#include <QtNetwork>
#include <QDebug>

#include "HttpDownloader.h"

HttpDownloader::HttpDownloader(QString url, QString dircetoryPath, QWidget *parent) :
	url(url), directoryPath(dircetoryPath), parent(parent) {
}

HttpDownloader::~HttpDownloader() {
}

void HttpDownloader::startDownload() {
    reply = qnam.get(QNetworkRequest(url));
    connect(reply, SIGNAL(finished()), this, SLOT(httpFinished()));
    connect(reply, SIGNAL(readyRead()), this, SLOT(httpReadyRead()));
    connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this,
            SLOT(updateDataReadProgress(qint64,qint64)));
}

bool HttpDownloader::downloadFile() {
	QFileInfo fileInfo(url.path());
	QString fileName = fileInfo.fileName();
	QDir directory(directoryPath);
	QString filePath = directory.filePath(fileName);

	file = new QFile(filePath);
	if (!file->open(QIODevice::WriteOnly)) {
		QMessageBox::information(parent, tr("HTTP"),
				tr("Unable to save the file %1: %2.").arg(fileName).arg(
						file->errorString()));
		delete file;
		file = 0;
		return false;
	}

	httpRequestAborted = false;
	startDownload();
	return true;
}

void HttpDownloader::cancelDownload() {
	qDebug() << "cancel";
	httpRequestAborted = true;
	if (reply) {
		reply->abort();
	}
}

void HttpDownloader::httpFinished() {
	qDebug() << "finished";
	if (httpRequestAborted) {
		qDebug() << "aborted";
		if (file) {
			file->close();
			file->remove();
			delete file;
			file = 0;
		}
		reply->deleteLater();
		reply = 0;
		return;
	}

	file->flush();
	file->close();

	QVariant redirectionTarget = reply->attribute(
			QNetworkRequest::RedirectionTargetAttribute);
	if (reply->error()) {
		qDebug() << "error";
		file->remove();
		QMessageBox::information(parent, tr("HTTP"),
				tr("Download failed: %1.").arg(reply->errorString()));
	} else if (!redirectionTarget.isNull()) {
		qDebug() << "redirect";
		url = url.resolved(redirectionTarget.toUrl());
		reply->deleteLater();
		file->open(QIODevice::WriteOnly);
		file->resize(0);
		startDownload();
		return;
	} else {
		qDebug() << "ok";
		reply->deleteLater();
		reply = 0;
		delete file;
		file = 0;
		emit downloadFinished();
		this->deleteLater();
	}
}

void HttpDownloader::httpReadyRead() {
	if (file) {
		file->write(reply->readAll());
	}
}

void HttpDownloader::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes) {
	if (totalBytes != 0) {
		emit progressUpdated((int) (bytesRead * 100 / totalBytes));
	}
}

